//
//  DialViewController.m
//  SIPphone
//
//  Created by wrt on 13-10-25.
//  Copyright (c) 2013年 wrtsoft. All rights reserved.
//

#import "DialViewController.h"
#import "AppDelegate.h"
#import "HistoryViewController.h"
#import "UserIDSettingViewController.h"
#import "CallViewController.h"
#import "AddContactsViewController.h"
#import "SoundEngine.h"
#import "ContactsDateBase.h"
#import "HistoryDataBase.h"
#import "FriendRespondDateBase.h"
#import "PromptChatDateBase.h"
#import "PostMessageDataBase.h"
#import "SimplePingHelper.h"


@interface DialViewController ()
@property (strong, nonatomic) NSString *trackViewUrl;
@end

@implementation DialViewController
@synthesize registButton = _registButton, numberTextField = _numberTextField,alertView = _alertView, button2 = _button2, button3 = _button3, button4 = _button4, button5 = _button5, button6 = _button6, button7 = _button7, button8 = _button8, button9 = _button9;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
//        self.title = NSLocalizedString(@"dial", @" 拨号 tabbar Item For dial name ");
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    //当页面显示时
    self.numberTextField.text = @"";   //将号码栏内的号码清空
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL registerStatus = [defaults boolForKey:@"REGISTERSTATUS"];
    //获取是否是登陆的状态
    if (registerStatus)
    {
        //若是登陆的状态则显示用户名在左上方
//        NSString *tempUserName = [[NSString alloc] init];
//        tempUserName = [defaults valueForKey:@"SAVEUSERNAME"];
//        [self.registButton setTitle:[NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"user", @"用户 user"),tempUserName] forState:UIControlStateNormal];
//        [self.registButton setEnabled:NO];
        [self.registButton setHidden:YES];
        [self.statusLabel setHidden:NO];
        [self.activityIndicator stopAnimating];
        [self.activityIndicator setHidden:YES];
        
        
        switch ([defaults integerForKey:@"SAVEMYSTATUS"])
        {
            case 0:
                self.statusLabel.text = NSLocalizedString(@"offline", @"离线 Offline");
                break;
            case 1:
                self.statusLabel.text = NSLocalizedString(@"online", @"在线 Online");;
                break;
            case 2:
                self.statusLabel.text = NSLocalizedString(@"busy", @"繁忙 Busy");
                break;
            case 6:
                self.statusLabel.text = NSLocalizedString(@"out", @"外出 Out");
                break;
            case 7:
                self.statusLabel.text = NSLocalizedString(@"DNDST", @"勿扰 DNDST");
                break;

                
            default:
                break;
        }
    }
    else
    {
//        [self.registButton setHidden:NO];
//        [self.statusLabel setHidden:YES];
//        //若不是登陆状态 则显示登录
//        [self.registButton setTitle:@"登录" forState:UIControlStateNormal];
       
    }
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    interface.delegate = self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor colorWithRed:225/255.0 green:225/255.0 blue:225/255.0 alpha:0.8];
    
    
    //判断版本号 然后选择相应导航栏的ui界面
    float systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (systemVersion >= 7.0) //7.0以上
    {
        UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 64)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 64)];
        label.backgroundColor = [UIColor clearColor];
        label.text = NSLocalizedString(@"dial", @" 拨号 tabbar Item For dial name ");
        label.font = [UIFont systemFontOfSize:18];
        label.textAlignment = NSTextAlignmentCenter;
        titleView.backgroundColor = [UIColor clearColor];
        [titleView addSubview:label];
        
        self.registButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.registButton setFrame:CGRectMake(0, 18, 60, 30)];
        [self.registButton setTitle:NSLocalizedString(@"login", @"登录 Login") forState:UIControlStateNormal];
        [self.registButton addTarget:self action:@selector(registButtonPressed) forControlEvents:UIControlEventTouchUpInside];
//        [self.registButton setBackgroundImage:[UIImage imageNamed:@"button_textured_30.png"] forState:UIControlStateNormal];
        [self.registButton setBackgroundColor:[UIColor clearColor]];
        [self.registButton setTitleColor:[UIColor colorWithRed:83/255.0 green:215/255.0 blue:105/255.0 alpha:1.0] forState:UIControlStateNormal];
        self.registButton.titleLabel.textAlignment = 0;
        [titleView addSubview:self.registButton];
        
        
        
        UIButton *historyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [historyButton setFrame:CGRectMake(260, 18, 27, 27)];
        [historyButton addTarget:self action:@selector(historyButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        [historyButton setBackgroundImage:[UIImage imageNamed:@"ic_calllog_outgoing_active.png"] forState:UIControlStateNormal];
        [titleView addSubview:historyButton];
        
        self.statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 18, 70, 30)];
        [self.statusLabel setBackgroundColor:[UIColor clearColor]];
        [self.statusLabel setTextAlignment:0];
        [self.statusLabel setTextColor:[UIColor grayColor]];
        [self.statusLabel setHidden:YES];
        [titleView addSubview:self.statusLabel];
        

        self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [self.activityIndicator setFrame:CGRectMake(80, 22, 20, 20)];
        [self.activityIndicator setHidden:YES];
        [titleView addSubview:self.activityIndicator];
        
        self.navigationItem.titleView = titleView;
    }
    else
    {
        UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 64)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 64)];
        label.backgroundColor = [UIColor clearColor];
        label.text = NSLocalizedString(@"dial", @" 拨号 tabbar Item For dial name ");;
        label.font = [UIFont systemFontOfSize:18];
        label.textAlignment = NSTextAlignmentCenter;
        titleView.backgroundColor = [UIColor clearColor];
        [titleView addSubview:label];
        
        self.registButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.registButton setFrame:CGRectMake(10, 18, 60, 30)];
        [self.registButton setTitle:NSLocalizedString(@"login", @"登录 Login") forState:UIControlStateNormal];
        [self.registButton addTarget:self action:@selector(registButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        //        [self.registButton setBackgroundImage:[UIImage imageNamed:@"button_textured_30.png"] forState:UIControlStateNormal];
        [self.registButton setBackgroundColor:[UIColor clearColor]];
        [self.registButton setTitleColor:[UIColor colorWithRed:83/255.0 green:215/255.0 blue:105/255.0 alpha:1.0] forState:UIControlStateNormal];
        self.registButton.titleLabel.textAlignment = 0;
        [titleView addSubview:self.registButton];
        
        
        
        UIButton *historyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [historyButton setFrame:CGRectMake(270, 18, 27, 27)];
        [historyButton addTarget:self action:@selector(historyButtonPressed) forControlEvents:UIControlEventTouchUpInside];
        [historyButton setBackgroundImage:[UIImage imageNamed:@"ic_calllog_outgoing_active.png"] forState:UIControlStateNormal];
        [titleView addSubview:historyButton];
        
        self.statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 18, 70, 30)];
        [self.statusLabel setBackgroundColor:[UIColor clearColor]];
        [self.statusLabel setTextAlignment:0];
        [self.statusLabel setTextColor:[UIColor grayColor]];
        [self.statusLabel setHidden:YES];
        [titleView addSubview:self.statusLabel];
        
        
        self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [self.activityIndicator setFrame:CGRectMake(90, 22, 20, 20)];
        [self.activityIndicator setHidden:YES];
        [titleView addSubview:self.activityIndicator];
        
        self.navigationItem.titleView = titleView;
        
    }
    
//    //注册按钮创建 设置在导航栏的左边
//    self.registButton = [[UIBarButtonItem alloc] initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(registButtonPressed)];
//    self.navigationItem.leftBarButtonItem = self.registButton;
    
    //历史纪录按钮创建 设置在导航栏的右边
//    UIBarButtonItem *historyButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ic_calllog_outgoing_active.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(historyButtonPressed)];

//    self.navigationItem.rightBarButtonItem = historyButton;
    
    //设置textfield代理
    self.numberTextField.delegate = self;
    
    //单例SIP设置代理进行监听
    SIPInterface *interface = [SIPInterface shareSIPInterface];
    interface.delegate = self;
    //获取存在程序内的用户名和密码和昵称/ip/端口
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *tempUserName = [[NSString alloc] init];
    tempUserName = [defaults valueForKey:@"SAVEUSERNAME"];
    NSString *tempPassWord = [[NSString alloc] init];
    tempPassWord = [defaults valueForKey:@"SAVEPASSWORD"];
    NSString *tempIp = [[NSString alloc] init];
    tempIp = [defaults valueForKey:@"SAVEIPADDRESS"];
    NSString *tempPort = [[NSString alloc] init];
    tempPort = [defaults valueForKey:@"SAVEPORT"];
    NSString *tempDisplayName = [[NSString alloc] init];
    tempDisplayName = [defaults valueForKey:@"SAVEDISPLAYNAME"];
    NSString *tempAppid = [[NSString alloc] init];
    tempAppid = [defaults valueForKey:@"SAVEAPPID"];
    BOOL isAutoRegister = [defaults boolForKey:@"ISAUTOREGISTERSTATUS"];
    
    BOOL isReachability = [defaults boolForKey:@"ISREACHABILITY"];
    
    BOOL isfirstLogBegin = [defaults boolForKey:@"ISFIRSTLOGBEGIN"];
    
    //若勾选了自动登陆并且程序存在已存的用户名和密码\ip\端口 以及 就自动登陆
    if (isAutoRegister && tempPassWord.length > 0 && tempUserName.length > 0 && tempIp.length > 0 && tempPort.length > 0 && tempDisplayName.length > 0 && isReachability && !isfirstLogBegin && tempAppid.length > 0)
    {
        [interface register:tempAppid passWord:tempPassWord];
        [interface displayName:tempDisplayName andUserName:tempAppid];
        [interface setServiceAddress:tempIp andPort:[tempPort intValue]];
//        [interface startRegisterUsers];
        
        [self.registButton setHidden:YES];
        [self.statusLabel setHidden:NO];
        self.statusLabel.text = NSLocalizedString(@"loading", @"登录中 Loading");
        [self.activityIndicator setHidden:NO];
        [self.activityIndicator startAnimating];
//        [self performSelector:@selector(autoRegisterWait) withObject:self];
    }
    if (isfirstLogBegin)
    {
        BOOL registerStatus = [defaults boolForKey:@"REGISTERSTATUS"];
        //获取是否是登陆的状态
        if (registerStatus)
        {
            //若是登陆的状态则显示用户名在左上方
            //        NSString *tempUserName = [[NSString alloc] init];
            //        tempUserName = [defaults valueForKey:@"SAVEUSERNAME"];
            //        [self.registButton setTitle:[NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"user", @"用户 user"),tempUserName] forState:UIControlStateNormal];
            //        [self.registButton setEnabled:NO];
            [self.registButton setHidden:YES];
            [self.statusLabel setHidden:NO];
            [self.activityIndicator stopAnimating];
            [self.activityIndicator setHidden:YES];
            
            
            switch ([defaults integerForKey:@"SAVEMYSTATUS"])
            {
                case 0:
                    self.statusLabel.text = NSLocalizedString(@"offline", @"离线 Offline");
                    break;
                case 1:
                    self.statusLabel.text = NSLocalizedString(@"online", @"在线 Online");;
                    break;
                case 2:
                    self.statusLabel.text = NSLocalizedString(@"busy", @"繁忙 Busy");
                    break;
                case 6:
                    self.statusLabel.text = NSLocalizedString(@"out", @"外出 Out");
                    break;
                case 7:
                    self.statusLabel.text = NSLocalizedString(@"DNDST", @"勿扰 DNDST");
                    break;
                    
                    
                default:
                    break;
            }
        }
    }
    else
    {
        [defaults setBool:NO forKey:@"REGISTERSTATUS"];
    }
    
    [defaults synchronize];
    
    //给来电和未接的状态设置通知，响应的方法是将对应的信息存入到数据库中
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callincomingAnswer11) name:@"INCOMINGCALLANSWER" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callincomingNotAnswer11) name:@"INCOMINGCALLNOTANSWER" object:nil];
    
    //设置关掉alertview的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertviewClose) name:@"ALERTVIEWCLOSEED" object:nil];
    
//    //这个界面上将扬声器打开
//    [[SoundEngine shareSound] LoudSpeaker:YES];
    
    //长按处理方法，添加到“x”这个按钮之上，这样短按是删，长按是清空
    UILongPressGestureRecognizer *btnLongTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(button0LongClick:)];
    btnLongTap.minimumPressDuration = 0.8;
    [self.button0 addGestureRecognizer:btnLongTap];
    
    [self checkUpdate];
}

//检查更新
- (void)checkUpdate
{
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (app.isRecodeOpenNumber%5 == 0)
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        BOOL isConnectNet = [defaults boolForKey:@"ISREACHABILITY"];
        if (isConnectNet == YES)
        {
            [self pingAddress:@"www.baidu.com"];
        }
    }
}

//自动登陆中，弹出等待框
- (void)autoRegisterWait
{
    //弹出警告窗口
    self.alertView = [[UIAlertView alloc] initWithTitle:@"自动登陆中..." message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    [self.alertView show];
    //在里面加入旋转
    UIActivityIndicatorView *activeView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    //开始转
    [activeView startAnimating];
    activeView.center = CGPointMake(self.alertView.bounds.size.width/2,self.alertView.bounds.size.height-40.0f);
    [self.alertView addSubview:activeView];
}

//注册按钮的处理方法 跳转到注册界面
- (void)registButtonPressed
{
    UserIDSettingViewController *registVC = [[UserIDSettingViewController alloc] initWithNibName:@"UserIDSettingViewController" bundle:nil];
    [self.navigationController pushViewController:registVC animated:YES];
}

//历史纪录按钮的处理方法  跳转到历史纪录界面
- (void)historyButtonPressed
{
    HistoryViewController *historyVC = [[HistoryViewController alloc] initWithNibName:@"HistoryViewController" bundle:nil];
    [historyVC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:historyVC animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//去除alert的窗口的方法、防止在别的viewcontron上退不去
- (void)alertviewClose
{
    [self.alertView dismissWithClickedButtonIndex:0 animated:YES];
}




#pragma mark -
#pragma mark numberButtonMethod
//按钮1操作
- (IBAction)button1Pressed:(id)sender
{
    self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"1"];
    SystemSoundID id = 1201;
    AudioServicesPlaySystemSound(id);
}
//按钮2操作
- (IBAction)button2Pressed:(id)sender
{
    self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"2"];
    SystemSoundID id = 1202;
    AudioServicesPlaySystemSound(id);
}
//按钮2按下触发手势
- (IBAction)button2PressedDown:(id)sender
{
    //手势左
    UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick2:)];
    swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.button2 addGestureRecognizer:swipeLeftGesture];
    
    //手势上
    UISwipeGestureRecognizer *swipeUpGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick2:)];
    swipeUpGesture.direction = UISwipeGestureRecognizerDirectionUp;
    [self.button2 addGestureRecognizer:swipeUpGesture];
    
    //手势下
    UISwipeGestureRecognizer *swipeDownGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick2:)];
    swipeDownGesture.direction = UISwipeGestureRecognizerDirectionDown;
    [self.button2 addGestureRecognizer:swipeDownGesture];
}

//手势处理方法
- (void)swipeGesterClick2:(UISwipeGestureRecognizer *)swipeGesture
{
    if(swipeGesture.direction == UISwipeGestureRecognizerDirectionLeft)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"B"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionUp)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"A"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionDown)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"C"];
    }
    SystemSoundID id = 1201;
    AudioServicesPlaySystemSound(id);
}

//按钮3操作
- (IBAction)button3Pressed:(id)sender
{
    self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"3"];
    SystemSoundID id = 1203;
    AudioServicesPlaySystemSound(id);
}
//按钮3按下触发手势
- (IBAction)button3PressedDown:(id)sender
{
    //手势左
    UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick3:)];
    swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.button3 addGestureRecognizer:swipeLeftGesture];
    
    //手势上
    UISwipeGestureRecognizer *swipeUpGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick3:)];
    swipeUpGesture.direction = UISwipeGestureRecognizerDirectionUp;
    [self.button3 addGestureRecognizer:swipeUpGesture];
    
    //手势下
    UISwipeGestureRecognizer *swipeDownGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick3:)];
    swipeDownGesture.direction = UISwipeGestureRecognizerDirectionDown;
    [self.button3 addGestureRecognizer:swipeDownGesture];
}
//手势处理方法
- (void)swipeGesterClick3:(UISwipeGestureRecognizer *)swipeGesture
{
    if(swipeGesture.direction == UISwipeGestureRecognizerDirectionLeft)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"E"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionUp)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"D"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionDown)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"F"];
    }
    SystemSoundID id = 1203;
    AudioServicesPlaySystemSound(id);
}


//按钮4操作
- (IBAction)button4Pressed:(id)sender
{
    self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"4"];
    SystemSoundID id = 1204;
    AudioServicesPlaySystemSound(id);
}
//按钮4按下触发手势
- (IBAction)button4PressedDown:(id)sender
{
    //手势左
    UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick4:)];
    swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.button4 addGestureRecognizer:swipeLeftGesture];
    
    //手势上
    UISwipeGestureRecognizer *swipeUpGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick4:)];
    swipeUpGesture.direction = UISwipeGestureRecognizerDirectionUp;
    [self.button4 addGestureRecognizer:swipeUpGesture];
    
    //手势下
    UISwipeGestureRecognizer *swipeDownGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick4:)];
    swipeDownGesture.direction = UISwipeGestureRecognizerDirectionDown;
    [self.button4 addGestureRecognizer:swipeDownGesture];
    
}
//手势处理方法
- (void)swipeGesterClick4:(UISwipeGestureRecognizer *)swipeGesture
{
    if(swipeGesture.direction == UISwipeGestureRecognizerDirectionLeft)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"H"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionUp)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"G"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionDown)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"I"];
    }
    SystemSoundID id = 1204;
    AudioServicesPlaySystemSound(id);
}

//按钮5操作
- (IBAction)button5Pressed:(id)sender
{
    self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"5"];
    SystemSoundID id = 1205;
    AudioServicesPlaySystemSound(id);
}
//按钮5按下触发手势
- (IBAction)button5PressedDown:(id)sender
{
    //手势左
    UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick5:)];
    swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.button5 addGestureRecognizer:swipeLeftGesture];
    
    //手势上
    UISwipeGestureRecognizer *swipeUpGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick5:)];
    swipeUpGesture.direction = UISwipeGestureRecognizerDirectionUp;
    [self.button5 addGestureRecognizer:swipeUpGesture];
    
    //手势下
    UISwipeGestureRecognizer *swipeDownGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick5:)];
    swipeDownGesture.direction = UISwipeGestureRecognizerDirectionDown;
    [self.button5 addGestureRecognizer:swipeDownGesture];
}
//手势处理方法
- (void)swipeGesterClick5:(UISwipeGestureRecognizer *)swipeGesture
{
    if(swipeGesture.direction == UISwipeGestureRecognizerDirectionLeft)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"K"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionUp)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"J"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionDown)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"L"];
    }
    SystemSoundID id = 1205;
    AudioServicesPlaySystemSound(id);
}


//按钮6操作
- (IBAction)button6Pressed:(id)sender
{
    self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"6"];
    SystemSoundID id = 1206;
    AudioServicesPlaySystemSound(id);
}
//按钮6按下触发手势
- (IBAction)button6PressedDown:(id)sender
{
    //手势左
    UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick6:)];
    swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.button6 addGestureRecognizer:swipeLeftGesture];
    
    //手势上
    UISwipeGestureRecognizer *swipeUpGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick6:)];
    swipeUpGesture.direction = UISwipeGestureRecognizerDirectionUp;
    [self.button6 addGestureRecognizer:swipeUpGesture];
    
    //手势下
    UISwipeGestureRecognizer *swipeDownGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick6:)];
    swipeDownGesture.direction = UISwipeGestureRecognizerDirectionDown;
    [self.button6 addGestureRecognizer:swipeDownGesture];
}
//手势处理方法
- (void)swipeGesterClick6:(UISwipeGestureRecognizer *)swipeGesture
{
    if(swipeGesture.direction == UISwipeGestureRecognizerDirectionLeft)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"N"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionUp)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"M"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionDown)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"O"];
    }
    SystemSoundID id = 1206;
    AudioServicesPlaySystemSound(id);
}


//按钮7操作
- (IBAction)button7Pressed:(id)sender
{
    self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"7"];
    SystemSoundID id = 1207;
    AudioServicesPlaySystemSound(id);
}
//按钮7按下触发手势
- (IBAction)button7PressedDown:(id)sender
{
    //手势左
    UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeGesterClick7:)];
    swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.button7 addGestureRecognizer:swipeLeftGesture];
    
    //手势上
    UISwipeGestureRecognizer *swipeUpGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick7:)];
    swipeUpGesture.direction = UISwipeGestureRecognizerDirectionUp;
    [self.button7 addGestureRecognizer:swipeUpGesture];
    
    //手势右
    UISwipeGestureRecognizer *swipeRightGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick7:)];
    swipeRightGesture.direction = UISwipeGestureRecognizerDirectionRight;
    [self.button7 addGestureRecognizer:swipeRightGesture];
    
    //手势下
    UISwipeGestureRecognizer *swipeDownGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick7:)];
    swipeDownGesture.direction = UISwipeGestureRecognizerDirectionDown;
    [self.button7 addGestureRecognizer:swipeDownGesture];
}
//手势处理方法
- (void)swipeGesterClick7:(UISwipeGestureRecognizer *)swipeGesture
{
    if(swipeGesture.direction == UISwipeGestureRecognizerDirectionLeft)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"Q"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionUp)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"P"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionRight)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"S"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionDown)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"R"];
    }
    SystemSoundID id = 1207;
    AudioServicesPlaySystemSound(id);
}

//按钮8操作
- (IBAction)button8Pressed:(id)sender
{
    self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"8"];
    SystemSoundID id = 1208;
    AudioServicesPlaySystemSound(id);
}
//按钮8按下触发手势
- (IBAction)button8PressedDown:(id)sender
{
    //手势左
    UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick8:)];
    swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.button8 addGestureRecognizer:swipeLeftGesture];
    
    //手势上
    UISwipeGestureRecognizer *swipeUpGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick8:)];
    swipeUpGesture.direction = UISwipeGestureRecognizerDirectionUp;
    [self.button8 addGestureRecognizer:swipeUpGesture];
    
    //手势下
    UISwipeGestureRecognizer *swipeDownGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick8:)];
    swipeDownGesture.direction = UISwipeGestureRecognizerDirectionDown;
    [self.button8 addGestureRecognizer:swipeDownGesture];

}
//手势处理方法
- (void)swipeGesterClick8:(UISwipeGestureRecognizer *)swipeGesture
{
    if(swipeGesture.direction == UISwipeGestureRecognizerDirectionLeft)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"U"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionUp)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"T"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionDown)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"V"];
    }
    SystemSoundID id = 1208;
    AudioServicesPlaySystemSound(id);
}


//按钮9操作
- (IBAction)button9Pressed:(id)sender
{
    self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"9"];
    SystemSoundID id = 1209;
    AudioServicesPlaySystemSound(id);
}
//按钮9按下触发手势
- (IBAction)button9PressedDown:(id)sender
{
    //手势左
    UISwipeGestureRecognizer *swipeLeftGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick9:)];
    swipeLeftGesture.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.button9 addGestureRecognizer:swipeLeftGesture];
    
    //手势上
    UISwipeGestureRecognizer *swipeUpGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick9:)];
    swipeUpGesture.direction = UISwipeGestureRecognizerDirectionUp;
    [self.button9 addGestureRecognizer:swipeUpGesture];
    
    //手势右
    UISwipeGestureRecognizer *swipeRightGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick9:)];
    swipeRightGesture.direction = UISwipeGestureRecognizerDirectionRight;
    [self.button9 addGestureRecognizer:swipeRightGesture];
    
    //手势下
    UISwipeGestureRecognizer *swipeDownGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesterClick9:)];
    swipeDownGesture.direction = UISwipeGestureRecognizerDirectionDown;
    [self.button9 addGestureRecognizer:swipeDownGesture];
}
//手势处理方法
- (void)swipeGesterClick9:(UISwipeGestureRecognizer *)swipeGesture
{
    if(swipeGesture.direction == UISwipeGestureRecognizerDirectionLeft)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"X"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionUp)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"W"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionRight)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"Z"];
    }
    else if(swipeGesture.direction == UISwipeGestureRecognizerDirectionDown)
    {
        self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"Y"];
    }
    SystemSoundID id = 1209;
    AudioServicesPlaySystemSound(id);
}

//按钮*操作
- (IBAction)buttonStarPressed:(id)sender
{
    self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"*"];
    SystemSoundID id = 1210;
    AudioServicesPlaySystemSound(id);
}

//按钮0操作
- (IBAction)button0Pressed:(id)sender
{
    self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"0"];
    SystemSoundID id = 1200;
    AudioServicesPlaySystemSound(id);
}

- (void)button0LongClick:(id)sender
{
    self.numberTextField.text = @"";
}

//按钮#操作
- (IBAction)buttonSharpPressed:(id)sender
{
    self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"#"];
    SystemSoundID id = 1211;
    AudioServicesPlaySystemSound(id);
}

//添加按钮的操作
- (IBAction)buttonAddPressed:(id)sender
{
    //若无号码点击 则直接push到添加界面
    if (self.numberTextField.text.length == 0)
    {
        AddContactsViewController *addContactsVC = [[AddContactsViewController alloc] init];
        [self.navigationController pushViewController:addContactsVC animated:YES];
    }//若有号码。将号码一起push过去
    else if (self.numberTextField.text.length > 0)
    {
        AddContactsViewController *addContactsVC = [[AddContactsViewController alloc] initWithNumber:self.numberTextField.text];
        [self.navigationController pushViewController:addContactsVC animated:YES];
    }
}

//拨号按钮操作
- (IBAction)buttonCallPressed:(id)sender
{
    //先判断是否是登陆状态，如果不是登陆状态则提示请登陆
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL registerStatus = [defaults boolForKey:@"REGISTERSTATUS"];
    if (registerStatus && self.numberTextField.text.length > 1)
    {
        SIPInterface *interface = [SIPInterface shareSIPInterface];
        
        if (self.numberTextField.text.length == 4)
        {
            NSString *tempFront = [self.numberTextField.text substringToIndex:2];
            NSString *tempLast = [self.numberTextField.text substringFromIndex:2];
            
            [interface start_Call:[NSString stringWithFormat:@"0755000201001010%@0%@01",tempFront,tempLast]];
        }
        else
        {
            [interface start_Call:self.numberTextField.text];
        }
        
        
        
        HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
        [historyDB writeIntoDatabaseWithNumber:self.numberTextField.text andDisplayName:self.numberTextField.text]; //将拨出的号码记录下来存到数据库中
    }
    else if(!registerStatus)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"please log in", @"请先登陆 Please log in") delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"好的 OK") otherButtonTitles: nil];
        [alert show];
    }
}

//删除按钮操作
- (IBAction)buttonDeletePressed:(id)sender
{
    if (self.numberTextField.text.length >= 1)
    {
        self.numberTextField.text = [self.numberTextField.text substringToIndex:self.numberTextField.text.length - 1];
    }
}



#pragma mark -
#pragma mark textFieldDelegateMethod
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    //防止出现系统键盘
    [self.numberTextField resignFirstResponder];
}

#pragma mark -
#pragma mark incomingSaveDataBase
- (void)callincomingAnswer11  //来电形式存数据库
{
    HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
    [historyDB callincomingAnswer];
}

- (void)callincomingNotAnswer11   //未接形式存数据库
{
    HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
    [historyDB callincomingNotAnswer];
}

#pragma mark -
#pragma mark SIPlistenMethod

- (void)registerSuccessful //注册成功时的操作
{
    dispatch_async(dispatch_get_main_queue(),^{
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *tempUserName = [[NSString alloc] init];
        tempUserName = [defaults valueForKey:@"SAVEUSERNAME"];
        [defaults setBool:YES forKey:@"REGISTERSTATUS"];
        [defaults synchronize];
//        [self.registButton setTitle:[NSString stringWithFormat:@"用户:%@",tempUserName]];
//        [self.registButton setTitle:[NSString stringWithFormat:@"用户:%@",tempUserName] forState:UIControlStateNormal];
//        [self.registButton setEnabled:NO];
        [self.registButton setHidden:YES];
        [self.statusLabel setHidden:NO];
        [self.activityIndicator stopAnimating];
        [self.activityIndicator setHidden:YES];
        
        switch ([defaults integerForKey:@"SAVEMYSTATUS"])
        {
            case 0:
                self.statusLabel.text = NSLocalizedString(@"offline", @"离线 Offline");
                break;
            case 1:
                self.statusLabel.text = NSLocalizedString(@"online", @"在线 Online");;
                break;
            case 2:
                self.statusLabel.text = NSLocalizedString(@"busy", @"繁忙 Busy");
                break;
            case 6:
                self.statusLabel.text = NSLocalizedString(@"out", @"外出 Out");
                break;
            case 7:
                self.statusLabel.text = NSLocalizedString(@"DNDST", @"勿扰 DNDST");
                break;
            default:
                break;
        }
        [self.alertView dismissWithClickedButtonIndex:0 animated:YES];
    });
    
    AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (app.isFristOpen == 1)
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        //个人状态 设置在线
        SIPInterface *interface = [SIPInterface shareSIPInterface];
        [interface setMyStatusWithInt:1];
        [defaults setInteger:1 forKey:@"SAVEMYSTATUS"];
        app.isFristOpen++;
        
        NSString *userName = [[NSString alloc] init];
        userName = [defaults valueForKey:@"SAVEUSERNAME"];
        //创建用于存储联系人的数据库
        ContactsDateBase *contactsDb = [ContactsDateBase shareContactsDataBase];
        [contactsDb changeTableName:userName];
        [contactsDb creatDB];
        [contactsDb readDB];
        
        //创建用于存储好友信息的数据库
        FriendRespondDateBase *friendRespondDB = [FriendRespondDateBase shareFriendRespondDateBase];
        [friendRespondDB changeTableName:userName];
        [friendRespondDB creatDB];
        [friendRespondDB readDB];
        
        //创建用于即时聊天的数据库
        PromptChatDateBase *promptDB = [PromptChatDateBase sharePromptChatDB];
        [promptDB changeTableName:userName];
        [promptDB creatDB];
        [promptDB readDB];
        
        //创建用于历史记录的数据库
        HistoryDataBase *historyDB = [HistoryDataBase shareHistoryDataBase];
        [historyDB changeTableName:userName];
        [historyDB createDb];
        [historyDB loadArray:0];
        
        //创建用于推送消息的数据库
        PostMessageDataBase *postMsgDB = [PostMessageDataBase sharePostMessageDateBase];
        [postMsgDB changeTableName:userName];
        [postMsgDB createDb];
        [postMsgDB loadArray];
        
//        NSMutableArray *tempUserNameArray = [[NSMutableArray alloc] init];
//        NSMutableArray *tempIpArray = [[NSMutableArray alloc] init];
        
        //将列表中的好友传到底层去
//        for (int i = 0; i < contactsDb.isFriendArray.count; i++)
//        {
//            if ([contactsDb.isFriendArray[i] isEqualToString:@"好友"])
//            {
//                [tempUserNameArray addObject:contactsDb.userNameArray[i]];
//                [tempIpArray addObject:contactsDb.ipPortArray[i]];
//            }
//        }
//        
//        for (int j = 0; j < tempUserNameArray.count; j++)
//        {
//            SIPInterface *interface = [SIPInterface shareSIPInterface];
//            [interface addFriendsWithUserName:tempUserNameArray[j]  andDisPlayName:@"" andIp:tempIpArray[j]];
//        }
        
        //注册报警服务器
        //=================================
        //报警配置
        //设置报警服务器地址和端口号
        NSString *alarmIPAddressStr = [[NSString alloc] init];
        alarmIPAddressStr = [defaults valueForKey:@"SAVEALARMIPADDRESS"];
        
        NSString *alarmIPPortStr = [[NSString alloc] init];
        alarmIPPortStr = [defaults valueForKey:@"SAVEALARMIPPORT"];
        
        if (alarmIPPortStr.length > 0 && alarmIPAddressStr.length > 0 )
        {
            [interface setAlarmIPAddressAndPort:alarmIPAddressStr andPort:alarmIPPortStr];
        }
    }
}

- (void)registerFailed  //注册失败时的操作
{
    dispatch_async(dispatch_get_main_queue(),^{
        [self.alertView dismissWithClickedButtonIndex:0 animated:YES];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", @"通知 notice") message:NSLocalizedString(@"automatic registration fails, check the network and re-visit", @"自动注册失败，请查看网络以及重新登陆 Automatic registration fails, check the network and re-visit") delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
        [alert show];
        [alert dismissWithClickedButtonIndex:0 animated:YES];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:NO forKey:@"REGISTERSTATUS"];
        [defaults synchronize];
//        [self.registButton setTitle:@"注册"];
        
        [self.registButton setHidden:NO];
        [self.statusLabel setHidden:YES];
        [self.activityIndicator stopAnimating];
        [self.activityIndicator setHidden:YES];
        //若不是登陆状态 则显示登录
        [self.registButton setTitle:NSLocalizedString(@"login", @"登录 Login") forState:UIControlStateNormal];
        
        [self.registButton setEnabled:YES];
    });
}

- (void)outgoingCallBegin  //主动呼叫开始
{
    dispatch_async(dispatch_get_main_queue(),^{
        CallViewController *callVC = [[CallViewController alloc] initWithNumber:self.numberTextField.text];
        callVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
        [self presentModalViewController:callVC animated:YES];
    });
}

- (void)callEnding
{
    
}

- (void)openWindow
{
    
}

#pragma mark -
#pragma mark pingMethod
- (void)pingAddress:(NSString *)addr
{
    [SimplePingHelper ping:addr target:self sel:@selector(pingResult:)];
}

// callback
- (void)pingResult:(NSNumber*)success
{
    if (success.boolValue)
    {
        //查找一个可用的全局队列
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        //将要做的操作放入队列
        dispatch_async(queue,^{
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:[NSURL URLWithString:@"http://itunes.apple.com/lookup?id=848903742"]];
            [request setHTTPMethod:@"GET"];
            NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
            NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:nil];
            
            NSString *latestVersion = [[NSString alloc] init];
            //地址trackViewUrl
            self.trackViewUrl = [[NSString alloc] init];
            //trackName
            NSString *trackName = [[NSString alloc] init];
            
            NSArray *releaseInfoArray = jsonData[@"results"];
            for (NSDictionary *releaseInfo in releaseInfoArray)
            {
                latestVersion =  [releaseInfo objectForKey:@"version"];
                self.trackViewUrl = [releaseInfo objectForKey:@"trackViewUrl"];
                trackName = [releaseInfo objectForKey:@"trackName"];
            }
            
            NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
            NSString *currentVersion = [infoDict objectForKey:@"CFBundleVersion"];
            double doubleCurrentVersion = [currentVersion doubleValue];
            double doubleUpdateVersion = [latestVersion doubleValue];
            
            dispatch_async(dispatch_get_main_queue(),^{
                if (doubleCurrentVersion < doubleUpdateVersion) {
                    
                    UIAlertView *alert;
                    alert = [[UIAlertView alloc] initWithTitle:trackName message:NSLocalizedString(@"A new version, you want to update", @"有新版本，你想要更新吗？ A new version, you want to update?") delegate: self cancelButtonTitle:NSLocalizedString(@"cancel", @"取消 cancel") otherButtonTitles: NSLocalizedString(@"Update", @"更新 Update"), nil];
                    alert.tag = 1002;
                    [alert show];
                }
            });
        });
    }
}


#pragma mark -
#pragma mark AlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1002)
    {
        if (buttonIndex == 0)
        {
            //取消
            NSLog(@"取消");
        }
        else if (buttonIndex == 1)
        {
            //跳转到AppStore
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.trackViewUrl]];
        }
    }
}

//dealloc中取消监听
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"INCOMINGCALLANSWER" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"INCOMINGCALLNOTANSWER" object:nil];
}


@end
